import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Content } from './entities/content.entity';
import { Tag } from '../tag/entities/tag.entity';
import { CreateContentDto } from './dto/create-content.dto';
import { UpdateContentDto } from './dto/update-content.dto';

@Injectable()
export class ContentService {
  constructor(
    @InjectRepository(Content)
    private contentRepository: Repository<Content>,
    @InjectRepository(Tag)
    private tagRepository: Repository<Tag>,
  ) {}

  async create(createContentDto: CreateContentDto) {
    const { tags, ...contentData } = createContentDto;
    
    const foundTags = await this.tagRepository.findByIds(tags);
    const content = this.contentRepository.create({
      ...contentData,
      tags: foundTags,
    });

    return await this.contentRepository.save(content);
  }

  async findAll(page: number = 1, pageSize: number = 10, type?: string) {  // 修改参数名
    const queryBuilder = this.contentRepository.createQueryBuilder('content')
      .leftJoinAndSelect('content.tags', 'tags')
      .orderBy('content.created_at', 'DESC')
      .skip((page - 1) * pageSize)  // 使用 pageSize
      .take(pageSize);  // 使用 pageSize

    if (type) {
      queryBuilder.where('content.type = :type', { type });
    }

    const [data, total] = await queryBuilder.getManyAndCount();

    return {
      list: data,
      pagination: {
        total,
        page,
        pageSize,  // 修改返回参数名
        totalPages: Math.ceil(total / pageSize)
      },
    };
  }

  async remove(id: number) {
    const content = await this.contentRepository.findOne({
      where: { id },
      relations: ['tags']
    });

    if (!content) {
      throw new NotFoundException(`ID为 ${id} 的内容不存在`);
    }

    await this.contentRepository.remove(content);
    return { message: '删除成功' };
  }

  async findOne(id: number) {
    const content = await this.contentRepository.findOne({
      where: { id },
      relations: ['tags']
    });

    if (!content) {
      throw new NotFoundException(`ID为 ${id} 的内容不存在`);
    }

    return content;
  }

  async update(id: number, updateContentDto: UpdateContentDto) {
    const content = await this.contentRepository.findOne({
      where: { id },
      relations: ['tags']
    });

    if (!content) {
      throw new NotFoundException(`ID为 ${id} 的内容不存在`);
    }

    // 如果有更新标签
    if (updateContentDto.tags) {
      const foundTags = await this.tagRepository.findByIds(updateContentDto.tags);
      content.tags = foundTags;
    }

    // 更新其他字段
    Object.assign(content, {
      ...updateContentDto,
      tags: content.tags // 保持标签不变，除非明确更新
    });

    return await this.contentRepository.save(content);
  }
}